<template>
	<view>
		<!-- 服务-模态层弹窗 -->
		<view class="popup service" :class="serviceClass" @touchmove.stop.prevent="discard" @tap="hideService">
			<!-- 遮罩层 -->
			<view class="mask"></view>
			<view class="layer" @tap.stop="discard">
				<view class="content">
					<view class="row" v-for="(item,index) in goodsData.service" :key="index">
						<view class="title">{{item.name}}</view>
						<view class="description">{{item.description}}</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 规格-模态层弹窗 -->
		<view class="popup spec" :class="specClass" @touchmove.stop.prevent="discard" @tap="hideSpec">
			<!-- 遮罩层 -->
			<view class="mask"></view>
			<view class="layer" @tap.stop="discard">
				<view class="content">
					<view class="sp">
						<view v-for="(item,index) in sku_list" :class="[index==selectSpec?'on':'']" @tap="setSelectSpec(index)" :key="index">{{item.spec_list[0].spec_value||'默认'}}</view>
					</view>
					<view class="length">
						<view class="text">数量</view>
						<van-stepper :value="buyGoodsNum" min="1" max="99" @plus="add(sku,index)" @minus="sub(sku,index)"/>
					</view>
				</view>
				<view class="btn"><view class="button" @tap="hideSpec">完成</view></view>
			</view>
		</view>
		<!-- 商品主图轮播 -->
		<view class="swiper-box">
			<swiper circular="true" autoplay="true" @change="swiperChange">
				<swiper-item v-for="(swiper,index) in goods.gallery_list" :key="swiper.sort">
					<image :src="swiper.big" :data-src="swiper.big" @tap="ViewImage" :data-url="index"></image>
				</swiper-item>
			</swiper>
			<view class="indicator" v-if="goods['gallery_list'].length">{{currentSwiper+1}}/{{goods['gallery_list'].length}}</view>
		</view>
		<!-- 标题 价格 -->
		<view class="info-box goods-info" style="margin-top: 30px;">
			<view class="text-sm margin-top-xs" style="color: #333;" v-if="descArr">
				<text>{{descArr[0]}}</text>
				<text style="text-decoration:line-through;">{{descArr[1]}}</text>
			</view>
			<view class="title text-xl margin-top-sm" style="min-height: 60rpx;">
				{{goods.goods_name || ''}}
			</view>
			<view class="price">
				<text class="text-df" style="color: #333;font-weight: 400;">售价:￥{{formatPrice(sku_list[0].price) || '0.00'}}</text>
			</view>
			<view class="price">
				<text class="text-df" style="color: #333;">妲粉价:</text><text class="text-xl text-bold" style="color: #f9720f;">￥{{formatPrice(sku_list[0].cost)|| '0.00'}}</text>
			</view>
			<view class="felx justify-end align-center margin-top-sm" style="display: flex;" v-if="visitNum&&visitNum>0">
				<text class="cuIcon-attentionfill"></text><text>已浏览{{visitNum||'0'}}人次</text>
			</view>
		</view>
		<!-- 服务-规则选择 -->
		<view class="info-box spec">
			<view class="row" @tap="showService">
				<view class="text">服务</view>
				<view class="content"><view class="serviceitem" v-if="index<2" v-for="(item,index) in goodsData.service" :key="index">{{item.name}}</view></view>
			</view>
			<view class="row">
				<view class="text text-black">规格</view>
				<view class="content">
					<view class="sp">
						<view v-for="(item,index) in sku_list" :key="index" :class="[index==selectSpec?'on':'']">{{item.spec_list[0].spec_value||'默认'}}</view>
					</view>
				</view>
			</view>
			<view class="row">
				<view class="text text-black">购买数量</view>
				<view class="content" style="flex:1;justify-content: flex-end;">
					<van-stepper :value="buyGoodsNum" min="1" max="99" @plus="add(sku,index)" @minus="sub(sku,index)"/>
				</view>
			</view>
		</view>
		<!-- 详情 -->
		<view class="description" id="description">
			<view class="title">———— 商品详情 ————</view>
			<view class="content">
				<view class="grace-rich-text">
				    <rich-text type="text" :nodes="demoHtml"></rich-text>
				</view>
			</view>
		</view>
		<view class="cu-modal bottom-modal" :class="modalName=='bottomModal'?'show':''" @tap="hideModal">
			<view class="cu-dialog">
				<view class="cu-bar bg-white">
					<view class="action text-green"></view>
					<view class="action text-blue" @tap="hideModal">取消</view>
				</view>
				<view class="padding-xl">
					<view class="cu-list flex justify-around">
						<view class="cu-item flex align-center" style="flex-direction: column;"  @tap="shareFc()">
							<image class="shareIcon" src="../../static/img/icon_poster.png" mode="widthFix"></image>
							<text>生成海报</text>
						</view>
						<view class="cu-item flex align-center" style="flex-direction: column;">
							<image style="z-index: 199" class="shareIcon" src="../../static/img/icon_weixin.png" mode="widthFix"></image>
							<text style="z-index: 199">分享微信好友</text>
							<button open-type='share' style="position: absolute;top:0; width: 100px; background:transparent;z-index: 999;;height:100px;border:0;border-color: #FFF;"></button>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="content">
			<view class="flex_row_c_c modalView" :class="qrShow?'show':''" @tap="hideQr()">
				<view class="flex_column">
					<view class="backgroundColor-white padding1vh border_radius_10px">
						<image :src="poster.finalPath" mode="widthFix" class="posterImage"></image>
					</view>
					<view class="flex_row marginTop2vh">
						<button type="primary" size="mini" @tap.prevent.stop="saveImage()">保存图片</button>
					</view>
				</view>
			</view>
			<view class="hideCanvasView">
				<canvas class="hideCanvas" canvas-id="default_PosterCanvasId" :style="{width: (poster.width||10) + 'px', height: (poster.height||10) + 'px'}"></canvas>
			</view>
		</view>
		<view class="popup" :class="modalName=='sharePoster'?'show':''"  @touchmove.stop.prevent="discard">
			<view class="mask"  @tap="hideModal"></view>
			<view class="layer1"  @tap.stop="discard">
				<view class="img-wrapper">
					<!-- 加上这个配置‘show-menu-by-longpress’，可以开启用户长按分享 -->
					<image 
						mode="widthFix"
						show-menu-by-longpress
						class="img-background" 
						:src="imgSrc"
					/>
					<!-- 仅为了展示二维码之用，实际使用可删除 -->
					<!-- <image class="img-qrcode" :src="testQRCodeSrc" /> -->
					<view class="flex align-center justify-around">
						<button @tap="hideModal()" class="btn" type="primary">取消</button>
						<button @tap="saveImg()" class="btn" type="primary">保存</button>
					</view> 
				</view>
			</view>		
		</view>
		<!-- <view class="cu-modal" :class="modalName=='sharePoster'?'show':''" style="display: fixed;top: 0;height: 100vh;" @tap="hideModal">
			
		</view> -->
		<view class="canvas-wrapper">
			<canvas class="canvas-background"  :style="{width: (simba.width||10) + 'px', height: (simba.height||10) + 'px'}" canvas-id="canvasBackground"></canvas>    
			<canvas class="canvas-qrcode" canvas-id="canvasQRCode"></canvas>
		</view>
		<view class="btn"><view class="button" @tap="saveImg()">完成</view></view>
		<view style="height:80rpx;"></view>
		<!-- 底部菜单 -->
		<view class="cu-bar bg-white tabbar foot border shop">
			<button class="action" @tap="showModal" data-target="bottomModal">
				<view class="cuIcon-share">
				</view>分享
			</button>
			<view class="action" @tap="GotoCart">
				<view class="cuIcon-cart">
					<view class="cu-tag badge" v-if="cartNum>0">{{cartNum}}</view>
				</view>
				购物车
			</view>
			<view class="btn-group">
				<button class="cu-btn bg-orange round shadow-blur" @tap="joinCart">加入购物车</button>
				<button class="cu-btn bg-red round shadow-blur" @tap="buy">立即购买</button>
			</view>
		</view>
	</view>
</template>

<script>
import _app from '@/util/QS-SharePoster/app.js';
import {getSharePoster} from '@/util/QS-SharePoster/QS-SharePoster.js';
import * as Goods_API from '../../api/goods.js'
import * as Cart_API from '../../api/cart.js'
var _self;
import graceRichText from '@/static/richText.js'
import {mapMutations} from 'vuex';
let drawQrcode = require('@/util/weapp.qrcpde.js')
import * as Foundation from '@/utils/Foundation.js'
export default {
	data() {
		return {
			goods_id:'',
			goods:{},
			cartNum:0,
			buyGoodsNum:1,
			poster: {},
			qrShow: false,
			canvasId: 'default_PosterCanvasId',
			showTop:false,//异常
			//轮播主图数据
			swiperList: [],
			//轮播图下标
			currentSwiper: 0,
			anchorlist:[],//导航条锚点
			selectAnchor:0,//选中锚点
			serviceClass: '',//服务弹窗css类，控制开关动画
			specClass: '',//规格弹窗css类，控制开关动画
			shareClass:'',//分享弹窗css类，控制开关动画
			// 商品信息
			goodsData:{
				service:[
					{name:"正品保证",description:"此商品官方保证为正品"},
					{name:"极速发货",description:"此商品享受退货极速发货服务"},
					{name:"48小时发货",description:"此商品享受付款后48小时发货服务"}
				]
			},
			selectSpec:null,//选中规格
			//商品描述html
			modalName: null,
			hasLogin:false,
			demoHtml:'',
			visitNum:0,
			sku_id:0,
			sku_list:[],//规格列表，
			shareImg:'',
			descArr:[],
			codeValue:'https://www.morekaba.com/applet/goods/',
			imgSrc:'',
			ratio:1,
			pixelRatio:1,
			simba:{
				width:0,
				height:0
			}					
		};
	},
	watch:{
		sku_id(new_val){
			this.sku_id =new_val
		}
	},
	onLoad(option) {
		if(option.goods_id || option.sku_id){
			this.goods_id = option.goods_id || option.sku_id
			this.goodsData.name = option.goods_id || option.sku_id
			this.GetGoodsDetail(option.goods_id|| option.sku_id)
			this.GoodsVisitNum(option.goods_id|| option.sku_id)
			this.GET_GoodsSku(this.goods_id)
		}
		if(option.shareUser){
			uni.setStorageSync('shareUser',{'shareU':option.shareUser})
		}
		if(option.phone){
			uni.setStorageSync('referrer',option.phone)
		}
		if (option.q) {
		     let queryAll = decodeURIComponent(option.q);
			 let phone = gup('phone', queryAll)
		     let sku_id = gup('sku_id', queryAll)
		     let shareUser = gup('shareUser', queryAll)
			 this.GetGoodsDetail(sku_id)
			 this.GoodsVisitNum(sku_id)
			 this.GET_GoodsSku(sku_id)
			 uni.setStorageSync('referrer',phone)
			 uni.setStorageSync('shareUser',{'shareU':shareUser})
		} 
	},
	onShow(e) {
		this.setSelectSpec(0)
		this.initData();
	},
	methods: {
		...mapMutations(['login']),
		// 数据初始化
		async initData() {
			this.hasLogin = uni.getStorageSync('userInfo').access_token;
			if(this.hasLogin){
				this.CartNum()
			}
		},
		formatPrice(price){
			return Foundation.formatPrice(price)
		},
		ChooseImage() {
			uni.chooseImage({
				count: 4, //默认9
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album'], //从相册选择
				success: (res) => {
					this.swiperList = res.tempFilePaths
				}
			});
		},
		navTo(route) {
		    if (!route) {
		        return;
		    }
		    if (!this.hasLogin) {
		        uni.showModal({
		            content: '你暂未登陆，是否跳转登录页面？',
		            success: (res) => {
		                if (res.confirm) {
		                    if(!uni.getStorageSync('isCanUse')){
		                    	uni.navigateTo({url:'../login/login'})
		                    }else{
		                    	uni.navigateTo({url: '../login/register'})
		                    }
		                }
		            }
		        });
		    } else {
		         uni.navigateTo({url: route})
		    }
		},
		// 商品查询
		GetGoodsDetail(goods_id){
			Goods_API.GetGoodsDetail(goods_id).then(res =>{
				this.goods = res
				this.demoHtml = graceRichText.format(res.intro);
				this.shareImg = res.show_image
				res.gallery_list.map(item =>{
					this.swiperList.push(item.big)
				})
				this.checkdesc(res.remark)
			})
		},
		// 查询商品规格
		GET_GoodsSku(goods_id){
			let that = this
			Goods_API.goodsSku(goods_id).then(res =>{
				this.sku_id = res[0].sku_id
				that.sku_list = res
			})
		},
		CartNum(){
			Cart_API.GetCartCount().then(res =>{
				if(res.result>0){
					this.cartNum = res.result
				}
			})
		},
		// 商品浏览人数
		GoodsVisitNum(goods_id){
			Goods_API.GoodsVisitNum(goods_id).then(res =>{
				this.visitNum = res
			})
		},
		//轮播图指示器
		swiperChange(event) {
			this.currentSwiper = event.detail.current;
		},
		ViewImage(e) {
			uni.previewImage({
				urls: this.swiperList,
				current: e.currentTarget.dataset.url
			});
		},
		checkdesc(desc){
			let descArr = []
			let descStr = desc
			let desc1 = ''
			let desc2 = ''
			let index = descStr.lastIndexOf("=")
			desc1 =descStr.substring(0,index+1);
			desc2 =descStr.substring(index+1,descStr.length);
			this.descArr[0]=desc1
			this.descArr[1]=desc2
		},
		GotoCart(){
			uni.switchTab({url:'../cart/cart'})
		},
		// // 分享
		share(){
			wx.showShareMenu({
			    withShareTicket: true
			})
		},
		onShareAppMessage() {
			let role_id = uni.getStorageSync('role').id
			let phone = uni.getStorageSync('userInfo').mobile
			let user = uni.getStorageSync('userInfo').nickname
			let title = ''
			let path = ''
			if(role_id){
				title = user + '分享的'+this.goods.goods_name+'等你抢购'
				path = '/pages/goods/goods?sku_id='+this.goods.goods_id+'&phone='+phone+'&shareUser='+user
			}else{
				title = this.goods.goods_name+'等你抢购'
				path = '/pages/goods/goods?sku_id='+this.goods.goods_id
			}
		    return {
				imageUrl: this.goods.gallery_list[0],
				title: title,
				path: path
		    }
		},
		// 加入购物车
		joinCart(){
			if (!this.hasLogin) {
			    uni.showModal({
			        content: '你暂未登陆，是否跳转登录页面？',
			        success: (res) => {
			            if (res.confirm) {
			                if(!uni.getStorageSync('isCanUse')){
			                	uni.navigateTo({url:'../login/login'})
			                }else{
			                	uni.navigateTo({url: '../login/register'})
			                }
			            }
			        }
			    });
			} else {
				wx.login({
				  success:async(res)=>{
					 let params = {
						code : res.code,
						sku_id : this.sku_id,
						num: parseInt(this.buyGoodsNum)
					}
					Cart_API.AddCart(params).then(res =>{
						if(res.sku_id){
							uni.setStorageSync('cartList', res);
							this.CartNum()
							uni.showModal({
								title: '温馨提示',
								content: '你已将商品加入购物车，你要去看看吗?',
								cancelText: '下次再说',
								confirmText: '去看看吧',
								success: res => {
									if (res.confirm) {
										uni.switchTab({url:'../cart/cart'})
									}
									if(res.cancel){
										uni.showToast({
											icon:'success',
											title:'已加入购物车'
										})
									}
								}
							})
						}
					})
				  },
				  fail:(rej) =>{
					  uni.showToast({
						icon:'fail',
						title:'登录失效'
					  })
				  }
				})
			}	
		},
		//立即购买
		buy(){
			// if(this.selectSpec==null){
			// 	this.setSelectSpec(0)
			// 	return this.showSpec(()=>{
			// 		this.toConfirmation()
			// 	});
			// }
			this.toConfirmation();
		},
		//跳转确认订单页面
		toConfirmation(){
			let params = {
				sku_id : this.sku_id,
				num : this.buyGoodsNum
			}
			if (!this.hasLogin) {
			    uni.showModal({
			        content: '你暂未登陆，是否跳转登录页面？',
			        success: (res) => {
			            if (res.confirm) {
			                if(!uni.getStorageSync('isCanUse')){
			                	uni.navigateTo({url:'../login/login'})
			                }else{
			                	uni.navigateTo({url: '../login/register'})
			                }
			            }
			        }
			    });
			} else {
			    Cart_API.Buy(params).then(res =>{
					if(res === 'SUCCESS'){
						Cart_API.GetAllCart().then(res =>{
							let CartData = res
							uni.setStorage({
								key:'buylist',
								data:CartData,
								success: () => {
									uni.navigateTo({
										url:'../goods/comfirmOrder'
									})
								}
							})
						})
					}else{
						uni.showToast({
							icon:'none',
							duration:2000,
							title:res.response.data.message
						})
					}
			    })
			}
		},
		//选择规格
		setSelectSpec(index){
			this.selectSpec = index;
		},
		//减少数量
		sub(){
			if(this.buyGoodsNum<=1){
				return;
			}
			this.buyGoodsNum--;
		},
		//增加数量
		add(){
			this.buyGoodsNum++;
		},
		// 点击回到顶部
		onPageScroll(e) {
			this.scrollTop = e.scrollTop
		  if (e.scrollTop > 500) {
			this.showTop = false;
		  } else {
			this.showTop = true;
		  }
		},
		goTop() {
		    uni.pageScrollTo({
		      scrollTop: 0,
		      duration: 300
		    })
		},
		//服务弹窗
		showService() {
			this.serviceClass = 'show';
		},
		//关闭服务弹窗
		hideService() {
			this.serviceClass = 'hide';
			setTimeout(() => {
				this.serviceClass = 'none';
			}, 200);
		},
		//规格弹窗
		showSpec(fun) {
			this.specClass = 'show';
			this.specCallback = fun;
		},
		specCallback(){
			return;
		},
		//关闭规格弹窗
		hideSpec() {
			this.specClass = 'hide';
			//回调
			this.selectSpec&&this.specCallback&&this.specCallback();
			this.specCallback = false;
			setTimeout(() => {
				this.specClass = 'none';
			}, 200);
		},
		// 分享 模态框底部
		showModal(e) {
			this.modalName = 'bottomModal'
		},
		hideModal(e) {
			this.modalName = null
		},
		async shareFc() {
			uni.showToast({
				icon:'loading',
				title:'加载中',
				duration:2500
			})
			let role_id = uni.getStorageSync('role').id
			let phone = uni.getStorageSync('userInfo').mobile
			let sku_id = this.goods.goods_id
			let user = uni.getStorageSync('userInfo').nickname
			const codeValue = this.codeValue
			let value = ''
			if(role_id){
				value = codeValue+'?sku_id='+sku_id+'&phone='+phone+'&shareUser='+user
			}else{
				value= codeValue+'?sku_id='+sku_id
			}
			let shareGoods = this.sku_list[0]
			let price = shareGoods.cost
			let descArr = []
			let descStr = this.goods.goods_name
			let desc1 = ''
			let desc2 = ''
			let index = this.goods.goods_name.lastIndexOf("赠")
			desc1 =descStr.substring(0,index);
			desc2 =descStr.substring(index,descStr.length);
			let goods_name = ''
			let goods_name_tips = ''
			if(index === -1){
				goods_name = this.goods.goods_name
			}else{
				goods_name = desc1
				goods_name_tips = desc2
			}			
			try {
				const d = await getSharePoster({
					_this: this, //若在组件中使用 必传
					type: 'testShareType',
					formData: {
						//访问接口获取背景图携带自定义数据
					},
					background:{
						width:1080,
						height:1920,
						backgroundColor:'#FFFFFF',					
					},
					backgroundColor:'#FFFFFF',
					// backgroundImage:'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2643472205,1029498831&fm=26&gp=0.jpg',
					posterCanvasId: this.canvasId,	//canvasId
					delayTimeScale: 10, //延时系数
					drawArray: ({
						bgObj,
						type,
						bgScale
					}) => {
						const dx = bgObj.width * 0.3;
						// console.log('bgObj',bgObj)
						const fontSize = bgObj.width * 0.05;
						const lineHeight = bgObj.height * 0.04;
						
						// console.log('二维码',value)
						//可直接return数组，也可以return一个promise对象, 但最终resolve一个数组, 这样就可以方便实现后台可控绘制海报
						return new Promise((rs, rj) => {
							rs([{
									type: 'custom',
									setDraw(Context) {
										Context.setFillStyle('#ac71cb');
										Context.setGlobalAlpha(1);
										Context.fillRect(0, bgObj.height - bgObj.height * 0.2, bgObj.width, bgObj.height * 0.2);
										Context.setGlobalAlpha(1);
									}
								},
								{
									type: 'image',
									url: this.shareImg,
									alpha: 1,
									dx:0,
									dy: 0,
									infoCallBack(imageInfo) {
										return {
											dWidth:bgObj.width, 
											dHeight: bgObj.height-280,
										}
									}
								},
								{
									type: 'text',
									fontStyle: 'italic',
									text: goods_name,
									size: fontSize,
									lineFeed: {
									    maxWidth: bgObj.width * 0.6,
									    lineHeight: 50,
									    lineNum: -1,
									    dx: -1
									},
									color: '#FFFFFF',
									alpha: 1,
									// textAlign: 'left',
									// textBaseline: 'middle',
									infoCallBack(textLength) {
										return {
											// dx: bgObj.width - textLength - fontSize-80,
											dx: bgObj.width * 0.1+200,
											dy: bgObj.height - lineHeight * 4
										}
									},
									serialNum: 0,
									id: 'tag1'	//自定义标识	
								},								
								{
									type: 'text',
									fontStyle: 'italic',
									text: goods_name_tips,
									size: fontSize,
									lineFeed: {
									    maxWidth: bgObj.width * 0.6,
									    lineHeight: 50,
									    lineNum: -1,
									    dx: -1
									},
									color: '#FFFFFF',
									alpha: 1,
									// textAlign: 'left',
									// textBaseline: 'middle',
									infoCallBack(textLength) {
										return {
											// dx: bgObj.width - textLength - fontSize-80,
											dx: bgObj.width * 0.1+200,
											dy: bgObj.height - lineHeight * 3
										}
									},
									serialNum: 0,
									id: 'tag1'	//自定义标识								
								},
								{
									type: 'text',
									text: '让美丽不迟到',
									size: fontSize*.8,
									color: 'white',
									alpha: 1,
									textAlign: 'left',
									textBaseline: 'middle',
									serialNum: 1,
									allInfoCallback({	//v3.0.1 更新 可以获取drawArray中全部数据
										drawArray
									} = {}) {
										const obj = drawArray.find(item => item.id === 'tag1');
										//也可以return promise对象
										return new Promise((rs, rj) => {
											setTimeout(() => {
												rs({
													dx: obj.dx,
													dy: obj.dy + lineHeight*2.2
												});
											}, 1);
										});
									}
								},
								{
									type: 'text',
									text: '赶快去扫码下单吧',
									size: fontSize*.8,
									color: 'white',
									alpha: 1,
									textAlign: 'left',
									textBaseline: 'middle',
									serialNum: 1,
									allInfoCallback({	//v3.0.1 更新 可以获取drawArray中全部数据
										drawArray
									} = {}) {
										const obj = drawArray.find(item => item.id === 'tag1');
										return new Promise((rs, rj) => {
											setTimeout(() => {
												rs({
													dx: obj.dx,
													dy: obj.dy + lineHeight*3.4
												});
											}, 1);
										});
									},
								},	
								{
									type: 'text',
									text: '￥'+price.toFixed(2),
									size: fontSize*1.3,
									color: 'white',
									alpha: 1,
									textAlign: 'left',
									textBaseline: 'middle',
									infoCallBack(textLength) {
										return {
											dx: bgObj.width - textLength-10 ,
											dy: bgObj.height - lineHeight*2.3
										}
									}
								},
								{
									type: 'qrcode',
									text: value,
									size: bgObj.width * 0.3,
									dx: bgObj.width * 0.1-60,
									dy: bgObj.height - bgObj.width * 0.32
								}
							]);
						})
					},
					setCanvasWH: ({
						bgObj,
						type,
						bgScale
					}) => { // 为动态设置画布宽高的方法，
						this.poster = bgObj;
					}
				});
				uni.hideLoading()
				this.poster.finalPath = d.poster.tempFilePath;
				this.qrShow = true;
			} catch (e) {
				_app.hideLoading();
				_app.showToast(JSON.stringify(e));
				// console.log(JSON.stringify(e));
			}
		},
		saveImage() {
			let that = this;
			wx.saveImageToPhotosAlbum({
				filePath: this.poster.finalPath,
				success(res) {
					_app.showToast('保存成功');
					that.hideQr()
				},
				fail(err) {
					_app.showToast('保存失败');
					that.hideQr()	
				}
			})
		},
		hideQr() {
			this.qrShow = false;
		},
		async sharePoster(){
			let phone = uni.getStorageSync('userInfo').mobile
			let sku_id = this.goods.goods_id
			let user = uni.getStorageSync('userInfo').nickname
			const codeValue = this.codeValue
			let value = codeValue+'?sku_id='+sku_id+'&phone='+phone+'&shareUser='+user
			
			this._getScreenRatio();
			wx.showLoading({ title: '图片加载中'});
						
			this.shareUrl = value
			let qrcodeSrc = await this._getGenerateQR();
						
			this._getImageInfo(qrcodeSrc);
			setTimeout(() => {
			    wx.hideLoading();
			}, 3000);		
		},
		/** 获取屏幕比例 */
		_getScreenRatio() {
			/** 设计稿里的屏幕宽度 */
			const ORI_WIDTH = 375;
			return new Promise(resolve => {
			    wx.getSystemInfo({
			        success: res => {
						console.log('1111',res)
			            this.ratio = ORI_WIDTH / res.windowWidth || 1
			            this.pixelRatio = res.pixelRatio || 3
			            resolve(null);
			        }
			        // 因为设置了ratio的默认初始值为1，所以这里不做false回调处理
			    });
			});	        
		},
		/** 获取网络图片转换为本地图片 */
		_getImageInfo(qrcodeSrc) {
			let shareImg = checkMPUrl(this.shareImg)
		    wx.getImageInfo({
		        src:shareImg,
		        success: res => {
		            this._drawImage(res.path, qrcodeSrc);
		        },
		        fail: err => {
		            console.error(
		                '_drawImage/wx.getImageInfo()',
		                '获取网络图片失败',
		                err
		            )
		        }
		    })
		},
		/** 根据链接生成动态二维码 */
		_getGenerateQR() {
		    const QRCodeWidth = 115 / this.ratio; // 是canvasQRCode的长宽除以2，即真实二维码图片的长宽除以2
		    const QRCodeHeight = 115 / this.ratio;
		    const CanvasId = 'canvasQRCode'; // 页面二维码canvas容器的ID，必须在页面添加canvas，且设置好长宽
		    return new Promise(resolve => {
		        drawQrcode({
		            width: QRCodeWidth,
		            height: QRCodeHeight,
		            canvasId: CanvasId,
		            text: this.shareUrl,
		            callback: e => {
		                // HACK: 安卓机上不准确，生成的二维码无法扫描，加延时解决
		                setTimeout(() => {
		                    // 将canvas保存至临时文件
		                    wx.canvasToTempFilePath({
		                        canvasId: CanvasId,
		                        success: res => {
		                            // 设置用于测试的二维码图片
		                            // this.testQRCodeSrc = res.tempFilePath
		                            resolve(res.tempFilePath);
		                        }
		                    });
		                }, 500);
		            }
		        });
		    });
		},
		/**
		* 绘制带二维码的背景图片
		 * @param {number} index 背景图片及canvas编号
		 * @param {String} backgroundImgPath 背景图片本地地址
		 * @param {String} qrcodeSrc 二维码图片本地临时地址
		 */
		_drawImage(backgroundImgPath, qrcodeSrc) {
			this.modalName = 'sharePoster'
			let shareGoods = this.sku_list[0]
			let price = shareGoods.cost
			let descArr = []
			let descStr = this.goods.goods_name
			let desc1 = ''
			let desc2 = ''
			let index = this.goods.goods_name.lastIndexOf("赠")
			desc1 =descStr.substring(0,index);
			desc2 =descStr.substring(index,descStr.length);
			let goods_name = ''
			let goods_name_tips = ''
			if(index === -1){
				goods_name = this.goods.goods_name
			}else{
				goods_name = desc1
				goods_name_tips = desc2
			}
		    // 图片尺寸常量
		    const backImgWidth = 325 * this.pixelRatio;
		    const backImgHeight = 650* this.pixelRatio;
			this.simba.width = backImgWidth
			this.simba.height =backImgHeight
		    /** 二维码绘制在图片中的宽度 */
		    const qrcodeWidth = 108 * this.pixelRatio;
		    /** 二维码绘制在图片中的高度 */
		    const qrcodeHeight = 108* this.pixelRatio;
			const fontSize = 20 *this.pixelRatio
		    // 准备画布,设置长宽
		    let ctx = wx.createCanvasContext('canvasBackground'); // 这个canvas必须是在页面里存在的
			ctx.fillStyle="#FFFFFF";
			ctx.fillRect(0,0, backImgWidth, backImgHeight);
		    ctx.drawImage(backgroundImgPath, 0, 0, backImgWidth, backImgHeight-qrcodeHeight-40); // 设置背景图片
			ctx.fillStyle="#ac71cb";
			ctx.fillRect(0,backImgHeight-qrcodeHeight-40, backImgWidth, backImgHeight-backImgWidth);
		    ctx.drawImage(qrcodeSrc, 20,backImgHeight-qrcodeHeight-20, qrcodeWidth, qrcodeHeight); // X坐标，Y坐标，二维码长，二维码宽
			ctx.fillStyle="#FFF";
			ctx.setFontSize(fontSize*1)
			ctx.fillText(goods_name,qrcodeWidth+30,backImgHeight-fontSize*5)
			ctx.fillText(goods_name_tips,qrcodeWidth+30,backImgHeight-fontSize*4)
			ctx.fillText('￥'+price,backImgWidth-160,backImgHeight-fontSize*3)
			ctx.setFontSize(fontSize*0.6)
			ctx.fillText('让美丽不迟到',qrcodeWidth+30,backImgHeight-fontSize*2)
			ctx.fillText('赶快去扫码下单吧',qrcodeWidth+30,backImgHeight-40)
		    ctx.draw(true, () => {
		        // 为了防止canvas资源转换失败，所以将资源转换放在draw的成功回调内执行
		        wx.canvasToTempFilePath({
		            canvasId: 'canvasBackground',
					quality:1,
		            success: res => {
						console.log(res)
		                this.imgSrc = res.tempFilePath
		                wx.hideLoading(); // 隐藏onload内的加载中
		            },
		            fail: err => {
		                console.error(
		                    '_drawImage/wx.canvasToTempFilePath()',
		                    '获取canvas临时图片地址失败',
		                    err
		                );
		            }
		        });
		    });
			this.modalName = 'sharePoster'
		},	
		saveImg() {
			let that = this;
			wx.saveImageToPhotosAlbum({
				filePath: this.imgSrc,
				success(res) {
					_app.showToast('保存成功');
					// that.hideQr()
					that.hideModal()
				},
				fail(err) {
					_app.showToast('保存失败');
					// that.hideQr()
						that.hideModal()
				}
			})
		},
		discard() {
			//丢弃
		}									
	}
};
function gup(name, url) {
  if (!url) url = location.href;
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(url);
  return results == null ? null : results[1];
}
function checkMPUrl(url) {
	// #ifdef MP
	if(
		url.substring(0, 4) === 'http' && 
		url.substring(0, 12) !== 'http://store' && 
		url.substring(0, 10) !== 'http://tmp' && 
		url.substring(0, 5) !== 'https'
	) {
		url = 'https' + url.substring(4, url.length);
	}
	// #endif
	return url;
}
</script>

<style lang="scss">
	.img-wrapper {
		  width: 100%;
		  text-align: center;
	}
	.img-background {  
		margin:0 50rpx;
		width: 500rpx;
		border-radius: 20rpx;
		background-color: #fff;
		padding: 20rpx;
		margin-top: 10px;
	}
	.canvas-qrcode,
	.img-qrcode {
		width: 230rpx;
		height: 230rpx;
	}	
	.canvas-wrapper {
		/* HACK: 隐藏canvas */
		position: fixed;
	}
	.grace-rich-text{padding:10upx 30upx;}
	page {
		background-color: #f8f8f8;
	}
	@keyframes showPopup {
		0% {
			opacity: 0;
		}
		100% {
			opacity: 1;
		}
	}
	@keyframes hidePopup {
		0% {
			opacity: 1;
		}
		100% {
			opacity: 0;
		}
	}
	@keyframes showLayer {
		0% {
			transform: translateY(0);
		}
		100% {
			transform: translateY(-100%);
		}
	}
	@keyframes hideLayer {
		0% {
			transform: translateY(-100%);
		}
		100% {
			transform: translateY(0);
		}
	}

.icon {
	font-size: 26upx;
}
.status {
	width: 100%;
	height: 0;
	position: fixed;
	z-index: 10;
	top: 0;
	/*  #ifdef  APP-PLUS  */
	height: var(--status-bar-height); //覆盖样式
	/*  #endif  */
	background-color: #f1f1f1;
	transition: opacity 0.05s linear;
}
.goTop image {
	height: 60rpx;
	width: 60rpx;
	border-radius: 100%;
	position: fixed;
	bottom: 150rpx;
	right: 60rpx;
	z-index: 100;
}
.swiper-box {
	position: relative;
	width: 100%;
	height: 90vw;
	swiper {
		width: 100%;
		height: 100vw;
		swiper-item {
			image {
				width: 100%;
				height: 100vw;
			}
		}
	}
	.indicator{
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 0 25upx;
		height: 40upx;
		border-radius: 40upx;
		font-size: 22upx;
		position: absolute;
		bottom: 20upx;
		right: 20upx;
		color: #fff;
		background-color: rgba(0, 0, 0, 0.2);
	}
}
.info-box {
	width: 100%;
	padding: 20upx 4%;
	background-color: #fff;
	margin-bottom: 20upx;
}

// .goods-info {
// 	.price {
// 		font-size: 36upx;
// 		font-weight: 500;
// 		color: #f9720f;
// 	}
	
// }
.spec {
	width: 100%;
	.row {
		width: 100%;
		display: flex;
		align-items: center;
		margin: 0 0 30upx 0;
		.text {
			font-size: 24upx;
			color: #333;
			margin-right: 20upx;
		}
		.content {
			font-size: 28upx;
			display: flex;
			flex-wrap: wrap;
			.serviceitem{
				margin-right: 10upx;
			}
			.sp {
				width: 100%;
				display: flex;
				view {
					background-color: #f6f6f6;
					padding: 5upx 10upx;
					color: #333;
					margin-right: 10upx;
					font-size: 24upx;
					border-radius: 5upx;
					&.on{
						border: solid 1upx #f47925;
						padding: 4upx 10upx;
					}
				}
			}
		}
		.arrow {
			position: absolute;
			right: 0%;
			.icon {
				color: #ccc;
			}
		}
	}
}
.comments {
	.row {
		width: 100%;
		height: 40upx;
		display: flex;
		align-items: center;
		margin: 0 0 30upx 0;
		.text {
			font-size: 30upx;
		}
		.arrow {
			font-size: 28upx;
			position: absolute;
			right: 4%;
			color: #17e6a1;
			.show {
				display: flex;
				align-items: center;
				.icon {
					color: #17e6a1;
				}
			}
		}
	}
	.comment {
		width: 100%;
		.user-info {
			width: 100%;
			height: 40upx;
			display: flex;
			align-items: center;
			.face {
				width: 40upx;
				height: 40upx;
				margin-right: 8upx;
				image {
					width: 40upx;
					height: 40upx;
					border-radius: 100%;
				}
			}
			.username {
				font-size: 24upx;
				color: #999;
			}
		}
		.content {
			margin-top: 10upx;
			font-size: 26upx;
		}
	}
}
.description {
	margin-bottom: 100upx;
	.title {
		width: 100%;
		height: 80upx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 26upx;
		color: #999;
		
	}
}
.footer {
	position: fixed;
	bottom: 0upx;
	width: 100%;
	padding: 0 4%;
	height: 99upx;
	border-top: solid 1upx #eee;
	background-color: #fff;
	z-index: 2;
	display: flex;
	justify-content: space-between;
	align-items: center;
	.icons {
		display: flex;
		height: 80upx;
		margin-left: -4%;
		.box {
			width: 80upx;
			height: 80upx;
			display: flex;
			justify-content: center;
			flex-wrap: wrap;
			.icon {
				font-size: 40upx;
				color: #828282;
			}
			.text {
				display: flex;
				justify-content: center;
				width: 100%;
				font-size: 22upx;
				color: #666;
			}
		}
	}
	.btn {
		height: 80upx;
		border-radius: 40upx;
		overflow: hidden;
		display: flex;
		margin-right: -2%;
		.joinCart,
		.buy {
			height: 80upx;
			padding: 0 40upx;
			color: #fff;
			display: flex;
			align-items: center;
			font-size: 28upx;
		}
		.joinCart {
			background-color: #f0b46c;
		}
		.buy {
			background-color: #f06c7a;
		}
	}
}
.popup {
	position: fixed;
	top: 0;
	width: 100%;
	height: 100%;
	z-index: 20;
	display: none;
	.mask{
		position: fixed;
		top: 0;
		width: 100%;
		height: 100%;
		z-index: 21;
		background-color: rgba(0, 0, 0, 0.6);
	}
	.layer1 {
		position: fixed;
		z-index: 1999;
		width: 100%;
		padding: 0 4%;
		height: 100%;
		border-radius: 20upx 20upx 0 0;
		// background-color: #fff;
		display: flex;
		flex-wrap: wrap;
		align-content: space-between;
	}
	.layer {
		position: fixed;
		z-index: 1999;
		bottom: -70%;
		width: 100%;
		padding: 0 4%;
		height: 70%;
		border-radius: 20upx 20upx 0 0;
		background-color: #fff;
		display: flex;
		flex-wrap: wrap;
		align-content: space-between;
		.content {
			width: 100%;
			padding: 20upx 0;
		}
		.btn {
			width: 100%;
			height: 100upx;
			.button {
				width: 100%;
				height: 80upx;
				border-radius: 40upx;
				color: #fff;
				display: flex;
				align-items: center;
				justify-content: center;
				background-color: #f47952;
				font-size: 28upx;
			}
		}
	}
	
	&.show {
		display: block;
		.mask{
			animation: showPopup 0.2s linear both;
		}
		.layer {
			animation: showLayer 0.2s linear both;
		}
	}
	&.hide {
		display: block;
		.mask{
			animation: hidePopup 0.2s linear both;
		}
		
		.layer {
			animation: hideLayer 0.2s linear both;
		}
	}
	&.none {
		display: none;
	}
	&.service {
		.row {
			margin: 30upx 0;
			.title {
				font-size: 30upx;
				margin: 10upx 0;
			}
			.description {
				font-size: 28upx;
				color: #999;
			}
		}
	}
	&.spec {
		.title {
			font-size: 30upx;
			margin: 30upx 0;
		}
		.sp {
			display: flex;
			view {
				font-size: 28upx;
				padding: 5upx 20upx;
				border-radius: 8upx;
				margin: 0 30upx 20upx 0;
				background-color: #f6f6f6;
				&.on {
					padding: 3upx 18upx;
					border: solid 1upx #f47925;
				}
			}
		}
		.length{
			margin-top: 30upx;
			border-top: solid 1upx #aaa;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding-top: 20upx;
			.text{
				font-size: 30upx;
			}
			.number{
				display: flex;
				justify-content: center;
				align-items: center;
				.input{
					width: 80upx;
					height: 60upx;
					margin: 0 10upx;
					background-color: #f3f3f3;
					display: flex;
					justify-content: center;
					align-items: center;
					text-align: center;
					input{
						width: 80upx;
						height: 60upx;
						display: flex;
						justify-content: center;
						align-items: center;
						text-align: center;
						font-size: 26upx;
					}
				}
				
				.sub ,.add{
					width: 60upx;
					height: 60upx;
					background-color: #f3f3f3;
					border-radius: 5upx;
					.icon{
						font-size: 30upx;
						width: 60upx;
						height: 60upx;
						display: flex;
						justify-content: center;
						align-items: center;
						
					}
				}
			}
		}
		
	}
}
.share{
	display: none;
	&.show {
		display: block;
		.mask{
			animation: showPopup 0.15s linear both;
		}
		.layer {
			animation: showLayer 0.15s linear both;
		}
	}
	&.hide {
		display: block;
		.mask{
			animation: hidePopup 0.15s linear both;
		}
		
		.layer {
			animation: hideLayer 0.15s linear both;
		}
	}
	&.none {
		display: none;
	}
	.mask{
		background-color: rgba(0,0,0,.5);
		position: fixed;
		width: 100%;
		height: 100%;
		top:0;
		z-index: 11;
	}
	.layer{
		width: 100%;
		position: fixed;
		z-index: 12;
		padding: 0 4%;
		top: 100%;
		background-color: rgba(255,255,255,0.9);
		.list{
			width: 100%;
			display: flex;
			padding:10upx 0 30upx 0;
			.box{
				width: 25%;
				display: flex;
				justify-content: center;
				flex-wrap: wrap;
				image{
					width: 13.8vw;
					height: 13.8vw;
				}
				.title{
					margin-top: 10upx;
					display: flex;
					justify-content: center;
					width: 100%;
					font-size: 26upx;
				}
			}
		}
		.btn{
			width: 100%;
			height: 100upx;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 28upx;
			border-top: solid 1upx #666666;
		}
		.h1{
			width: 100%;
			height: 80upx;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 34upx;
		}
	}
}
	.shareIcon{
		width: 70upx;
		margin-bottom: 10upx;
		z-index: 19;
	}
	/deep/.cu-bar.foot {
		z-index: 19;
	}
	.hideCanvasView {
		position: relative;
	}
	.hideCanvas {
		position: fixed;
		top: -99999upx;
		left: -99999upx;
		z-index: -99999;
	}
	.flex_row_c_c {
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}
	.modalView {
		width: 100%;
		height: 100%;
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		opacity: 0;
		outline: 0;
		transform: scale(1.2);
		perspective: 2500upx;
		background: rgba(0, 0, 0, 0.6);
		transition: all .3s ease-in-out;
		pointer-events: none;
		backface-visibility: hidden;
		z-index: 999;
	}
	.modalView.show {
		opacity: 1;
		transform: scale(1);
		pointer-events: auto;
	}
	.flex_column {
		display: flex;
		flex-direction: column;
		width: 70%;
	}
	.backgroundColor-white {
		background-color: white;
	}
	.border_radius_10px {
		border-radius: 10px;
	}
	.padding1vh {
		padding: 1vh;
	}
	.posterImage {
		width: 100%;
	}
	.flex_row {
		display: flex;
		flex-direction: row;
		justify-content: center;
	}
	.marginTop2vh {
		margin-top: 2vh;
	}
	/deep/button::after{
		border:0
	}
</style>
